package com.lxy.dataservice.service;

import cn.hutool.core.util.StrUtil;
import com.lxy.dataservice.constants.MessageConstants;
import com.lxy.dataservice.dao.MemberDao;
import com.lxy.dataservice.entity.Member;
import com.nip.db.mongodb.utils.tips.Response;
import com.nip.db.mongodb.utils.tips.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * MemberService
 *
 * @author < a href=" ">BBB</ a>
 * @version v1.0.01
 * @date 2019-12-26 14:36
 */
@Service
public class MemberService {
  @Autowired
  private MemberDao memberDao;

  /**
   * 保存会员(并作卡号重复判断)
   */
  public Response saveMember(Member entity) {
    try {
      Member member = memberDao.findAllByCardNumber(entity.getCardNumber());
      if (StrUtil.isEmpty(entity.getId())) {
        if (StringUtils.isEmpty(member)) {
          memberDao.save(entity);
          return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
        } else {
          return new Response(ResponseCode.CODE_202, "卡号重复");
        }
      } else {
        Member member1 = memberDao.findById(entity.getId()).orElse(null);
        if (member1.getCardNumber().equals(entity.getCardNumber())) {
          memberDao.save(entity);
          return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
        } else {
          if (StringUtils.isEmpty(member)) {
            memberDao.save(entity);
            return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
          } else {
            return new Response(ResponseCode.CODE_202, "卡号重复");
          }
        }
      }
    } catch (Exception e) {
      return new Response(ResponseCode.CODE_202, e.getMessage());
    }
  }

  /**
   * 查找所有会员
   */
  public List<Member> findAllMember() {
    return memberDao.findAll();
  }

  /**
   * 根据id查会员
   */
  public Member findById(String id) {
    return memberDao.findById(id).orElse(new Member());
  }

  /**
   * 删除会员
   */
  public Response deleteById(String id) {
    try {
      memberDao.deleteById(id);
      return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
    } catch (Exception e) {
      return new Response(ResponseCode.CODE_202, e.getMessage());
    }
  }

  /**
   * 根据卡号查会员(模糊)
   */
  public List<Member> findAllByCardNumber(String cardNumber) {
    return memberDao.findAllByCardNumberLike(cardNumber);
  }
}
